package com.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeUtil {
	/**
	 * 序列化对象工具类，用于保存和读取redis数据使用
	 */

	/**
	 * 序列化
	 * @param value
	 * @return
	 */
	public static byte[] serialize(Object value) {
		if (value == null) {
			throw new NullPointerException("Can't serialize null");
		}
		byte[] rv = null;
		ByteArrayOutputStream bos = null;
		ObjectOutputStream os = null;
		try {
			bos = new ByteArrayOutputStream();
			os = new ObjectOutputStream(bos);
			os.writeObject(value);
			os.close();
			bos.close();
			rv = bos.toByteArray();
		} catch (IOException e) {
			throw new IllegalArgumentException("Non-serializable object", e);
		} finally {
			try {
				if (os != null)
					os.close();
				if (bos != null)
					bos.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return rv;
	}
	/**
	 * 反序列化
	 * @param value
	 */
	public static Object deserialize(byte[] in) {
		Object rv = null;
		ByteArrayInputStream bis = null;
		ObjectInputStream is = null;
		try {
			if (in != null) {
				bis = new ByteArrayInputStream(in);
				is = new ObjectInputStream(bis);
				rv = is.readObject();
				is.close();
				bis.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null)
					is.close();
				if (bis != null)
					bis.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return rv;
	}

	public static void main(String[] args) {
//		List<Record> list=new ArrayList<Record>();
//		Record r1=new Record();
//		r1.set("name", "mwg");
//		r1.set("pwd", "123");
//		Record r2=new Record();
//		r2.set("name", "dxj");
//		r2.set("pwd", "321");
//		list.add(r1);
//		list.add(r2);
//		
//		byte[] in=serialize(list);
//		RedisUtil.setCache("testabc", in);
//		
//		byte[] out=RedisUtil.getCache("testabc");
//		List<Record> list2=(List<Record>) deserialize(out);
//		
//		for(int i=0;i<list2.size();i++)
//		{
//			Record res=list2.get(i);
//			System.out.println(res.getStr("name")+":::"+res.getStr("pwd"));
//		}
		
//		String testStr="mwgsdfadsf:sadf{}afads";
//		byte[] in=serialize(testStr);
//		RedisUtil.setCache("testabcd", in);
//		byte[] out=RedisUtil.getCache("testabcd");
//		System.out.println(deserialize(out));
		
	}
}
